<template>
  <el-card>
    <el-tabs v-if="role === 'user'" v-model="businessType" @tab-click="handleQuery">
      <el-tab-pane label="外卖订单" :name="1"></el-tab-pane>
      <el-tab-pane label="旧物订单" :name="2"></el-tab-pane>
    </el-tabs>
    <base-table
        ref="tableRef"
        v-loading="loading"
        :action="['query', 'operation']"
        :data="tableData"
        :fields="tableFields"
        :operation-width="180"
        :total="total"
        @add="handleAdd"
        @delete="handleDelete"
        @edit="handleEdit"
        @query="handleQuery"
        @batch-delete="handleBatchDelete"
    >
      <!-- 自定义搜索字段 -->
      <template #search-fields="{ searchForm }">
      </template>

      <template #orderItems="{ row }">
        <base-image :size="70" :src="row.orderItems.map(e => e.image)"></base-image>
      </template>
      <template #merchantId="{row}">
        {{ row.merchantName }}
      </template>
      <template #userId="{row}">
        {{ row.userName }}
      </template>
      <template #addressId="{row}">
        {{ row.address }}
      </template>
      <template #totalPrice="{row}">
        <span class="price"> ￥{{ row.totalPrice }}</span>
      </template>
      <template #deliveryFee="{row}">
        <span class="price"> ￥{{ row.deliveryFee }}</span>
      </template>

      <!-- 自定义操作列 -->
      <template #operations="{ row }">
        <el-button icon="view" link type="primary" @click="handleEdit(row)">查看详情</el-button>
        <el-button v-if="row.status === 4 && role === 'user'" icon="star" link type="warning"
                   @click="handleOpenReview(row)">评价
        </el-button>
        <el-button v-if="role === 'admin'" icon="delete" link type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </base-table>

    <!-- 表单对话框 -->
    <base-dialog
        ref="dialogRef"
        :fields="formFields"
        :title="dialogTitle"
        @submit="handleSubmit"
    />

    <OrderDetailDialog ref="orderDialog"></OrderDetailDialog>
    <ReviewDialog ref="reviewDialog"></ReviewDialog>
  </el-card>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {confirm} from '@/utils/utils.js'
import request from '@/utils/request'
import BaseTable from "@/components/common/BaseTable.vue";
import BaseDialog from "@/components/common/BaseDialog.vue";
import {fields} from '@/model/DishOrder.js'
import OrderDetailDialog from "@/components/OrderDetailDialog.vue";
import BaseImage from "@/components/common/BaseImage.vue";
import {useStore} from "vuex";
import ReviewDialog from "@/components/ReviewDialog.vue";

const orderDialog = ref(null)
const handleEdit = (row) => {
  orderDialog.value.open(row.id)
}

const reviewDialog = ref(null)
const handleOpenReview = (row) => {
  reviewDialog.value.open(row.orderItems)
}

const dishFields = ['merchantId']
const businessType = ref(1)
const role = computed(() => useStore().state.userInfo.role)
const tableFields = computed(() => {
  return [
    {
      prop: 'orderItems',
      label: '订单图片',
      type: 'text',
      width: '110',
    },
    ...fields
  ].filter(e => {
    if (role === 'merchant' && ['merchantId'].includes(e.prop)) {
      return false
    }
    if (businessType.value === 2 && dishFields.includes(e.prop)) {
      return false
    }
    return true;
  })
})

// 初始化
onMounted(async () => {
  await handleQuery()
  const remoteFields = fields.filter(field => field.type === 'remote-select' && field.search)
  for (let field of remoteFields) {
    field.options = await field.api()
  }
})

// 查询相关
const total = ref(0)
const tableData = ref([])
const tableRef = ref(null)
const loading = ref(false)
const handleQuery = async () => {
  try {
    loading.value = true
    const query = tableRef.value?.getQueryParam() || {}
    if (role.value === 'user') {
      query.param.businessType = businessType.value
    }

    const res = await request.post('/order/page', query)
    tableData.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 表单相关
const dialogRef = ref(null)
const dialogTitle = ref(null)
let formFields = computed(() => {
  return fields
})

const handleAdd = () => {
  dialogTitle.value = '新增外卖订单'
  dialogRef.value.open({})
}

const handleSubmit = async (formData) => {
  if (formData?.id) {
    await request.put('/order', formData)
    ElMessage.success('更新成功')
  } else {
    await request.post('/order', formData)
    ElMessage.success('添加成功')
  }
  dialogRef.value.close()
  await handleQuery()
}

// 处理删除
const handleDelete = (row) => {
  confirm(`确定要删除该外卖订单吗？`, async () => {
    await request.delete(`/order/${row.id}`)
    ElMessage.success('删除成功')
    await handleQuery()
  })
}

// 处理批量删除
const handleBatchDelete = (rows) => {
  confirm(`确定要删除选中的 ${rows.length} 个外卖订单吗？`, async () => {
    await Promise.all(rows.map(row => request.delete(`/order/${row.id}`)))
    ElMessage.success('批量删除成功')
    await handleQuery()
  })
}
</script>

<style scoped>
</style>